local skynet = require "skynet"
local pcall = (require "utils.call").pcall

local msg_center = {}

function msg_center.setMessageHandler(teyp_handler,id,handler,enable)

    enable = enable or true

    local handlers = teyp_handler[id]
    if not handlers then
        teyp_handler[id] = {}
        handlers = teyp_handler[id]
    end

    local index = -1
    for i,v in ipairs(handlers) do
        if handler == v then
            index = i
            break
        end
    end

    if enable then
        if index ~= -1 then
            return false
        end
        table.insert(handlers,handler)
    else
        if -1 == index then
            return false
        end
        table.remove(handlers,index)
    end

    return true

end

function msg_center.dispatchMessage(type_handlers,id,...)
    skynet.error("msg_center dispatchMessage id:" .. tostring(id))
    local handlers = type_handlers[id]
    if handlers then
        for _,v in ipairs(handlers) do
            pcall(v,...)
        end
    else
        skynet.error("msg_center not find handler! id:" .. tostring(id))
    end
end

local default_msg_handlers = {}

function msg_center.setDefaultMessageHandler(id,handler,enable)
    return msg_center.setMessageHandler(default_msg_handlers,id,handler,enable)
end

function msg_center.dispatchDefaultMessage(id,...)
    msg_center.dispatchMessage(default_msg_handlers,id,...)
end

function msg_center.clearAllDefault()
    default_msg_handlers = {}
end

return msg_center